package iit.projects.etaxi.view.converters;

import iit.projects.etaxi.util.Constants;
import iit.projects.etaxi.util.JSFUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.DateTimeConverter;


/**
 * Converter for Date fields
 */
public class InputDateConverter extends DateTimeConverter implements Converter{
	
	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
	        SimpleDateFormat sdf = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
	        Date nDate;
	        if (value != null && !value.isEmpty()){
		        try {
		             nDate = sdf.parse(value);
		        } catch (ParseException ex) {
		        	 FacesMessage message = new FacesMessage();
		             message.setDetail(JSFUtils.getStringFromBundle(
		            		 Constants.BundleNames.MESSAGES, "javax.faces.converter.DateTimeConverter.DATE_detail").concat(Constants.COMMON_DATE_FORMAT));
		             message.setSummary("Date is missing or not valid");
		             message.setSeverity(FacesMessage.SEVERITY_ERROR);
		             throw new ConverterException(message);
		        }
		        return nDate;
	        }
	     return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
		Date date = (Date) value;
		SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
	    return dateFormat.format(date);
	}

}